package com.sxu.demo;

import java.time.DayOfWeek;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 任务调度线程池的应用 —— 定时任务
 * 假设需要 每周四 下午六点准时执行任务
 */
public class Test9 {
    public static void main(String[] args) {
        // 一周的时间间隔
        long period = 1000 * 60 * 60 * 24 * 7;
        // 当前时间
        LocalDateTime now = LocalDateTime.now();
        // 本周的周四
        LocalDateTime time = now.withHour(18).withMinute(0).withSecond(0).withNano(0).with(DayOfWeek.THURSDAY);
        // 如果过了周四，则获取下周周四
        if(now.compareTo(time) > 0) {
            time = time.plusWeeks(1);
        }
        // 获取间隔时间
        long initialDelay = Duration.between(now,time).toMillis();
        ScheduledExecutorService pool = Executors.newScheduledThreadPool(1);
        pool.scheduleAtFixedRate(()->{
            System.out.println("周四 18：00 running");
        },initialDelay,period, TimeUnit.MILLISECONDS);

    }
}
